<%@ include file="/common/taglibs.jsp"%>
<!--分页查询共用的页面-->
<%@ include file="/common/common.jsp"%>
<%@ include file="/common/dateUtil.jsp"%>
<%@ page language="java" pageEncoding="UTF-8"%>
<head>
<!--载入数据操作工具类-->
<script src="<%=jsPath%>/util/xlsx.core.min.js?v=8503021" type="text/javascript" ></script>   


<style>
/*信息块外层样式*/
.dap_imp_BodyDiv_css{
    width:600px;
    border: 1px solid rgb(228,228,228);
    border-radius: 3px;
    overflow: auto;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    align-items: flex-start;
}
.dap_imp_BodyDiv_css > span {
    width:100%;
    margin-top:10px;
}

.dap_imp_toolDiv{
    margin-top:10px;
    width:100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}


</style>





<script>

//////////////////////////////////////////////////////////////////////////////变量
var dap_imp = {};//定义导入数据相关方法对象
dap_imp.debug = true;//定义调试标记
dap_imp.data = {};
dap_imp.data.termDatas = [];//终端数据
dap_imp.data.vehDatas = [];//车辆数据
dap_imp.data.insertList = [];
dap_imp.data.insertDatas = {};//需要插入的数量

dap_imp.data.url = globalConfig.webPath +  "/dataProcess/insertOneVehData.action";
dap_imp.data.existNum = 0;//已存在车辆数量
dap_imp.data.sucNum = 0;//插入成功数量
dap_imp.data.errNum = 0;//插入失败数量
dap_imp.data.errList = [];//定义错误信息列表

dap_imp.flg = {};
dap_imp.flg.insertFlg = true;//插入标记，表示是否可以插入到数据库，用于停止和继续
dap_imp.flg.insertIndex = 0;//插入标记，表示已经完成的数据数量


//////////////////////////////////////////////////////////////////////////////初始化控件

//接口，初始化控件
dap_imp.initDivs = function(){
    this.initVehFileDiv();
    this.initTermFileDiv();
}

//初始化车辆文件控件
dap_imp.initVehFileDiv = function(){
    let that = this;
    $("#dap_imp_vehFile").change(function(e){
        let files = e.target.files;

        //初始化数据
        $("#dap_imp_vehFileName").html("");
        that.data.vehDatas = [];

        if (files.length > 0) {
            that.formatExcelFile(files,"veh");
            $("#dap_imp_vehFileName").html(files[0].name);
        }else{
            that.showInfo("没有选择车辆数据文件！")
        }
    });
}

//初始化终端文件控件
dap_imp.initTermFileDiv = function(){
    let that = this;
    $("#dap_imp_termFile").change(function(e){
        let files = e.target.files;

        //初始化数据
        $("#dap_imp_termFileName").html("");
        that.data.termDatas = [];

        if (files.length > 0) {
            that.formatExcelFile(files,"term");
            $("#dap_imp_termFileName").html(files[0].name);
        }else{
            that.showInfo("没有选择终端数据文件！")
        }
    });
}


//解析excel表格文件并保存数据
dap_imp.formatExcelFile = function(files,type){
    let that = this;
    let msg = "";
    try {
        let fileReader = new FileReader();
        fileReader.onload = function (ev) {
            try {
                var data = ev.target.result,
                    workbook = XLSX.read(data, {
                        type: 'binary'
                    }), // 以二进制流方式读取得到整份excel表格对象
                    persons = []; // 存储获取到的数据
            } catch (e) {
                console.error('文件类型不正确');
                msg += "文件类型不正确!";
                return;
            }
            // 表格的表格范围，可用于判断表头是否数量是否正确
            let fromTo = '';
            // 遍历每张表读取
            for (var sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'];
                    // console.log(fromTo);
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    break; // 如果只取第一张表，就取消注释这行
                }
            }
            // DataUtil.outDebug("person :" , persons);
            //保存数据到缓存
            if(type == "term"){
                that.data.termDatas = persons;
                that.showInfo("解析终端数据成功,共计解析 " + that.data.termDatas.length + " 条终端数据!");
                that.outDebug("vehData : " , that.data.termDatas);
            }else if(type == "veh"){
                that.data.vehDatas = persons;
                that.showInfo("解析车辆数据成功,共计解析 " + that.data.vehDatas.length + " 条车辆数据!");
                that.outDebug("termData : " , that.data.vehDatas);
            }
        };

        // 以二进制方式打开文件
        if (files.length > 0) {
            if(type == "veh"){
                that.showInfo("开始解析车辆数据......");
            }else{
                that.showInfo("开始解析终端数据......");
            }
            fileReader.readAsBinaryString(files[0]);
        }
    } catch (error) {
        msg += "解析excel表格失败:" + error;
        that.showInfo("解析excel表格失败 ，数据类型：" + type + " ， 失败信息：" + error);
    }
    return msg;
}


//////////////////////////////////////////////////////////////////////////////开始整合数据

//开始整合两个数据
dap_imp.format2Data = function(){
    let that = this;
    let msg = "";
    try {
        //初始化数据
        that.data.insertList = [];
        that.data.insertDatas = {};

        if (that.data.vehDatas.length > 0 && that.data.termDatas.length > 0) {
            //整合车辆数据
            that.showInfo("开始整合车辆数据......");
            let total = that.data.vehDatas.length;
            let num = 0;
            $.each(that.data.vehDatas, function (n, item) {
                let obj = that.getOneVehData(n,item);
                if (obj.message == "") {
                    that.data.insertList.push(obj.plateNo);
                    that.data.insertDatas[obj.plateNo] = obj;
                } else {
                    //数据失败
                    that.showInfo(obj.message);
                    num++;
                }
            });
            let successNum = total - num;
            that.showInfo("整合车辆数据完成,总数：" + total + "辆 ，成功 ：" + successNum + " 辆 ， 失败：" + num + " 辆！");

            //整合终端数据
            if (that.data.termDatas.length > 0) {
                that.showInfo("开始整合终端数据......");
                total = that.data.termDatas.length;
                num = 0;
                $.each(that.data.termDatas,function(m,data){
                    let resultStr = that.insertTermData(m,data);
                    //整合失败
                    if(resultStr != ""){
                        num ++;
                        that.showInfo(resultStr);
                    }
                });
                successNum = total - num;
                that.showInfo("整合终端数据完成,总数：" + total + "辆 ，成功 ：" + successNum + " 辆 ， 失败：" + num + " 辆！");
            } else {
                that.showInfo("终端数据数量为0，无需整合!")
            }

            that.showInfo("整合数据完成,总数：" + that.data.insertList.length);
            that.outDebug("整合后的数据：" , that.data.insertDatas);
            
        } else {
            this.showInfo("车辆数据或者终端数据数量为0，无法整合数据！");
        }   
    } catch (error) {
        this.showInfo("整合车辆数失败：" + error);
    }
}

//获取一条车辆数据
dap_imp.getOneVehData = function(index,obj){
    let that = this;
    let temp = {message:""};
    let num = index + 1;
    if(!DataUtil.isDefined(obj)){
        let mustList = ["plateNo","plateColor","simNo","depName","useType","installDate"];
        $.each(mustList,function(i,item){
            if(!DataUtil.isDefined(obj[item])){
                if(obj[item] != ""){
                    if(item != "plateColor"){
                        temp[item] = obj[item];
                    }else{
                        temp[item] = that.getPlateColor(obj[item]);
                    }
                }else{
                    temp.message += " 数值：" + item + "为空！";
                }
            }else{
                temp.message += " 数值：" + item + "不存在！";
            }
        });

        let list = ["seqNo","endDate"];
        $.each(list,function(i,item){
            if(!DataUtil.isDefined(obj[item])){
                if(obj[item] != ""){
                    temp[item] = obj[item];
                }
            }else{
                temp.message += " 数值：" + item + "不存在！";
            }
        });
    }else{
        temp.message = "车辆对象不存在！";
    }

    if(temp.message != ""){
        if(!DataUtil.isDefined(temp.plateNo)){
            temp.message = temp.plateNo + "：" + temp.message;
        }
        temp.message = "第" + num + "条车辆数据-->" + temp.message;
    }

    return temp;
}

//获取车牌颜色
dap_imp.getPlateColor = function(plateColor){
    let value = 0;
    let color = '' + plateColor;
    switch (color) {
        case '蓝色':
            value = 1;
            break;
        case '黄色':
            value = 2;
            break;
        case '黑色':
            value = 3;
            break;
        case '白色':
            value = 4;
            break;
        case '其他':
            value = 5;
            break;
        case '黄绿':
            value = 6;
            break;

    }
    return value;
}


//插入一条终端数据
dap_imp.insertTermData = function(index,data){
    let msg = "";
    let num = index + 1;
    if(!DataUtil.isDefined(data)){
        if(!DataUtil.isDefined(data.plateNo)){
            let obj = this.data.insertDatas[data.plateNo];
            if(!DataUtil.isDefined(obj)){
                let list = ["termNo","termType"];
                $.each(list, function (n, item) {
                    if(!DataUtil.isDefined(data[item])){
                        if(data[item] != ""){
                            obj[item] = data[item];
                        }else{
                            if(item == "termType"){
                            obj[item] = "";
                        }else{
                            msg += " 数值：" + item + "为空!";
                        }
                        }
                    }else{
                        msg += " 数值：" + item + "不存在!";
                    }
                });
                //判断
            }else{
                msg += "获取车辆数据失败！"
            }
            
        }else{
            msg += "plateNo不存在";
        }
        
    }else{
        msg += "数据不存在";
    }

    if(msg != ""){
        if(!DataUtil.isDefined(data.plateNo)){
            msg = data.plateNo + "：" + msg;
        }
        msg = "第" + num + "条终端数据-->" + msg;
    }

    return msg;
}


//////////////////////////////////////////////////////////////////////////////插入数据至数据库

// 插入数据库
dap_imp.insertAllDatasToServer = function(){
    let that = this;
    $.messager.confirm("询问","确定开始插入车辆数据至数据库？",function(res){
        if(res){
            //开始插入
            that.flg.insertIndex = 0;
            that.data.existNum = 0;
            that.data.sucNum = 0;
            that.data.errNum = 0;
            that.data.errList = [];
            that.showInfo("开始插入数据至数据库......");
            that.insertOneDataToServer();
        }
    });
}

//递归插入方法
dap_imp.insertOneDataToServer = function(){
    let that = this;
    if(that.flg.insertFlg ==  true){
        if(that.flg.insertIndex < that.data.insertList.length){
            that.showInfo("开始插入第 " + (that.flg.insertIndex + 1) + " 条数据.....");
            //开始插入
            let item = that.data.insertList[that.flg.insertIndex];
            let obj = that.data.insertDatas[item];
            if(!DataUtil.isDefined(obj)){
                Utility.getAjaxData(that.data.url,JSON.stringify(obj),function(data){
                    // that.outDebug("data:",data);
                    let indexStr = "序号：" + (that.flg.insertIndex + 1) + " ，  车牌号：" + obj.plateNo +   "--->";
                    if(data.success){
                        if(data.data == 1){
                            that.data.sucNum ++;
                            that.showInfo(indexStr + "插入车辆成功！");
                        }else{
                            that.data.existNum ++;
                            that.showInfo(indexStr + "车辆已经存在，无需添加！");
                        }  
                    }else{
                        that.data.errNum ++;
                        let err = indexStr + "插入数据失败,失败原因：" + data.message;
                        that.showInfo(err);
                        that.data.errList.push(err);
                    }

                    //标记递增
                    that.flg.insertIndex++;
                    //继续插入
                    that.insertOneDataToServer();
                });
            }else{
             that.showInfo(indexStr + "获取车辆数据失败！")   
            }
        }else{
            that.showInfo("插入完成")
            that.showInsertNumInfo();
        }
    }else{
        that.showInfo('停止插入......');
        that.showInsertNumInfo();
    }
}

//显示插入数量
dap_imp.showInsertNumInfo = function(){
    let total = this.data.existNum + this.data.errNum + this.data.sucNum;
    this.showInfo("总共处理车辆数为：" + total + " 辆" );
    this.showInfo("已经存在车辆数量：" + this.data.existNum + " ， 新插入数量 ：" + this.data.sucNum + " ， 插入失败数量：" + this.data.errNum);
}




//////////////////////////////////////////////////////////////////////////////控件事件

//导入车辆数据点击事件
dap_imp.vehDataClickFun = function(){
    $("#dap_imp_vehFile").trigger("click");
};

//导入终端数据点击事件
dap_imp.termDataClickFun = function(){
    $("#dap_imp_termFile").trigger("click");
};

//停止点击事件
dap_imp.stopInsert = function(){
    if(this.flg.insertFlg == true){
        this.flg.insertFlg = false;
        $("#dep_imp_stopInsert_a").html("继续插入数据库");
    }else{
        this.flg.insertFlg = true;
        $("#dep_imp_stopInsert_a").html("停止插入数据库");
        this.insertOneDataToServer();
    }
}

//打印错误信息
dap_imp.printErrInfo = function(){
    let that = this;
    if(that.data.errList.length > 0){
        $.each(that.data.errList,function(n,item){
            that.showInfo(item);
        });
    }else{
        that.showInfo("没有错误信息需要打印!")
    }
}


//清空信息
dap_imp.clearMsgDiv = function(){
    $("#dap_imp_msgDiv").html("");
}

//////////////////////////////////////////////////////////////////////////////公用方法

//显示信息
dap_imp.showInfo = function(msg){
    let timeStr = Utility.dateToString(new Date());
    let html = '<span>&nbsp;&nbsp;&nbsp;&nbsp;[' + timeStr + ']  '+  msg + '</span>';
    $("#dap_imp_msgDiv").prepend(html);
}

//输出调试信息
dap_imp.outDebug = function(msg, data){
    if(this.debug == true){
        DataUtil.outDebug(msg,data);
    }
}

//////////////////////////////////////////////////////////////////////////////加载后执行
$(document).ready(function(){
    dap_imp.initDivs();
    dap_imp.showInfo("ready");
});




//////////////////////////////////////////////////////////////////////////////测试

</script>



</head>
<body>
    <div class="base_ver_flexStartDiv_css base_border228_css" style="width:600px;border-radius: 3px;">
        <div><span style="font-size:24px;">车辆数据导入页面</span></div>
        <div class="dap_imp_toolDiv">
            <a href="#" onclick="dap_imp.vehDataClickFun();">点我导入车辆数据</a>
            <input type="file" id="dap_imp_vehFile" style="display:none;">
        </div>
        <div class="dap_imp_toolDiv">
            <span>车辆数据文件：</span>
            <span id="dap_imp_vehFileName"></span>
        </div>
        <div class="dap_imp_toolDiv">
            <a href="#" onclick="dap_imp.termDataClickFun();">点我导入终端数据</a>
            <input type="file" id="dap_imp_termFile" style="display:none;">
        </div>
        <div class="dap_imp_toolDiv">
            <span>终端数据文件：</span>
            <span id="dap_imp_termFileName"></span>
        </div>
        <div class="base_hori_spaceAroundDiv_css" style="margin-top:10px;margin-bottom:10px;width:100%;">
            <a href="#" onclick="dap_imp.format2Data();">开始整合数据</a>
            <a href="#" onclick="dap_imp.insertAllDatasToServer();">插入数据到数据库</a>
            <a id="dep_imp_stopInsert_a" href="#" onclick="dap_imp.stopInsert();">停止插入数据库</a>
        </div>
    </div>
    <div class="base_hori_flexCenterDiv_css" style="width:600px;color:red;margin-top:10px;">
        <a href="#" onclick="dap_imp.clearMsgDiv();">清空信息</a>
        <span >&nbsp;&nbsp;&nbsp;&nbsp; 信息：&nbsp;&nbsp;&nbsp;&nbsp;<a href="#" onclick="dap_imp.printErrInfo();">打印本次上传错误信息</a></span>
    </div>
    <div id="dap_imp_msgDiv" class="dap_imp_BodyDiv_css" style="height:400px;">
        
    </div>
    
</body>